/* eslint-disable @typescript-eslint/no-explicit-any */
import qs from 'qs';
import { getToken } from '../util/util';

type RequestOptions = UniApp.RequestOptions & {
  query?: Record<string, any>;
};

/**
 * UniApp请求拦截器
 */
const httpInterceptor = {
  invoke(options: RequestOptions): void {
    // 接口请求支持通过 query 参数配置 queryString
    if (options.query) {
      const queryStr = qs.stringify(options.query);
      if (options.url.includes('?')) {
        options.url += `&${queryStr}`;
      } else {
        options.url += `?${queryStr}`;
      }
    }
    // 请求超时
    options.timeout = 10000;
    // 请求头
    options.header = {
      platform: ibiz.env.mobPlatform,
      Authorization: `Bearer ${getToken()}`,
    };
    // 设置系统Id
    let systemId = ibiz.env.dcSystem;
    const { orgData } = ibiz;
    if (orgData) {
      if (orgData.systemid) {
        systemId = orgData.systemid;
      }
      if (orgData.orgid) {
        options.header.srforgid = orgData.orgid;
      }
    }
    options.header.srfsystemid = systemId;
  },
};

/**
 * UniApp请求拦截器注册
 */
export const UniAppRequestInterceptor = {
  install(): void {
    // 拦截 request 请求
    uni.addInterceptor('request', httpInterceptor);
    // 拦截 uploadFile 文件上传
    uni.addInterceptor('uploadFile', httpInterceptor);
  },
};
